//
//  ViewController.m
//  LiWuShuo
//
//  Created by 袁小航 on 14/11/12.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "ViewController.h"
#import "Define.h"
#import "Selection.h"
#import "ProductCollectionViewCell.h"
#import "ProDetailViewController.h"
#import "SelectModel.h"
#import <UIImageView+WebCache.h>
#import "MBProgressHUD.h"
#import "ProCollectButton.h"
#import "MJRefresh.h"
#import "AppDelegate.h"
#import "Collect.h"
#import <UIButton+WebCache.h>
#import "ShowProViewController.h"



@interface ViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UIScrollViewDelegate>

@property(nonatomic, retain) Selection *selection;
@property(nonatomic, assign) NSInteger pageNum;
@property(nonatomic, retain) NSMutableArray *selData;
@property(nonatomic, retain) NSArray *selTopData;

@property(nonatomic, retain) MBProgressHUD *mbview;

//定义一个nsinteger变量来保存刷新数据的页数
@property(nonatomic, assign) NSInteger page;

//定义一个NSManagedObjectContext类型的对象
@property(nonatomic, retain) NSManagedObjectContext *managedObjectContex;

//不论成功与否 收藏后都弹出的alert
@property(nonatomic, retain) UIAlertView *CollAlert;
@property(nonatomic, retain) UIAlertView *CollFailAlert;

//定义一个数组用来保存database中的数据
@property(nonatomic, retain) NSArray *DBData;

@end

@implementation ViewController

-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden = NO;
    self.tabBarController.tabBar.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:240/255.0 green:59/255.0 blue:59/255.0 alpha:1];
    
    UILabel * typeTitle = [[UILabel alloc]init];
    typeTitle.text = @"爱优礼物";
    typeTitle.textColor = [UIColor whiteColor];
    typeTitle.font = [UIFont systemFontOfSize:16];
    typeTitle.frame = CGRectMake(0, 0, 40, 30);
    self.navigationItem.titleView = typeTitle;
    
//    设置AppDelegate的代理  使用coreData保存数据
    AppDelegate *delegate = [UIApplication sharedApplication].delegate;
    self.managedObjectContex = delegate.managedObjectContext;
    
//    获取Top图片数据
    [self getTopData];
    
//    创建rootCollectionView
    [self createRootCollectionView];
    
//    刷新
    [self setupRefresh];
    
//    创建MBView
    [self createMBView];
    
}
#pragma mark - MBView
-(void)createMBView
{
    self.mbview = [[MBProgressHUD alloc] initWithView:self.view];
    self.mbview.labelText = @"loading...";
    [self.mbview setMode:MBProgressHUDModeIndeterminate];
    [self.mbview show:YES];
    [self.view addSubview:self.mbview];
}

#pragma mark - 刷新
-(void)setupRefresh
{
    _page = 0;
    [_selection.rootCollectionView addHeaderWithTarget:self action:@selector(headerRershing)];
    [_selection.rootCollectionView headerBeginRefreshing];
    
    [_selection.rootCollectionView addFooterWithTarget:self action:@selector(footRershing)];
    [_selection.rootCollectionView footerEndRefreshing];
}
-(void)headerRershing
{
//    [self.AllDate removeAllObjects];
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self getData:_page];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [_selection.rootCollectionView headerEndRefreshing];
    });
}
- (void)footRershing
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        _page = _page + 12;
        // 刷新表格
        [self getData:_page];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [_selection.rootCollectionView footerEndRefreshing];
    });
}

#pragma mark -
#pragma mark getData
- (void)getData:(NSInteger)page
{
    NSURLSessionTask * model = [SelectModel globalTimelinePostsWithBlock:^(NSArray *posts, NSError *error) {
        if (_page == 0) {
            self.selData = [NSMutableArray arrayWithArray:posts];
            [_selection.rootCollectionView reloadData];
            [self.mbview removeFromSuperview];
        } else {
            [self.selData addObjectsFromArray:posts];
            [_selection.rootCollectionView reloadData];
        }
    } page:page];
    
}

#pragma mark - 
#pragma mark - getTopData
- (void)getTopData
{
    NSURLSessionDataTask *topModel = [SelectModel selectionTopImageWithBlock:^(NSArray *posts, NSError *errot) {
        if (!errot) {
            self.selTopData = [NSArray arrayWithArray:posts];
            //            设置scrollView 以及page
            [self topView];
            //            给scrollView附图片
            [self TopScrollViewImage];
            
            [_selection.rootCollectionView reloadData];
        }
    }];
    
}

#pragma mark -
#pragma mark 给scrollView附图片
- (void)TopScrollViewImage
{
    for (int i = 0; i < _selTopData.count ; i++) {
        _selection.rootImageButton = [[UIButton alloc]initWithFrame:CGRectMake(MAIN_SCREEN_WIDTH * i, 0, MAIN_SCREEN_WIDTH, SELVIEW_SCROLL_HEIGHT)];
//        给image赋tag值
        _selection.rootImageButton.tag = i + 1000;
        [_selection.rootImageButton addTarget:self action:@selector(rootImageButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        
        [_selection.rootImageButton setBackgroundImageWithURL:[NSURL URLWithString:[_selTopData[i]selTopImageUrl]] forState:UIControlStateNormal placeholderImage:nil];
        [_selection.rootScrollView addSubview:_selection.rootImageButton];
    }
}
#pragma mark - rootImageButtonAction
- (void)rootImageButtonAction:(UIButton *)sender
{
    UIButton *imageButton = sender;
    if ([_selTopData[(imageButton.tag - 1000)] selTopID] != nil) {
        NSString *contentUrl = [NSString stringWithFormat:@"http://www.liwushuo.com/posts/%@/content", [_selTopData[imageButton.tag - 1000] selTopID]];
        ProDetailViewController *proVC = [[ProDetailViewController alloc]init];
        proVC.proDetailUrl = contentUrl;
        [self.navigationController pushViewController:proVC animated:YES];
        NSLog(@"%@", contentUrl);
    } else {
        ShowProViewController *showVC = [[ShowProViewController alloc]init];
        showVC.subType = @"Topic";
        showVC.subID = [[_selTopData[(imageButton.tag - 1000)] selTopicId] integerValue];
        showVC.subTitle = [_selTopData[(imageButton.tag - 1000)] selTopicTitle];
        [self.navigationController pushViewController:showVC animated:YES];
    }
}
#pragma mark -
#pragma mark 设置scrollView 以及page
- (void)topView
{
    _selection.rootScrollView.contentSize = CGSizeMake(MAIN_SCREEN_WIDTH * _selTopData.count, ROOT_SEL_SCROLL_HEIGHT);
    
    //    设置top滚动视图自动滚动
    [self AutoScroll];
    
    _selection.rootScrollView.delegate = self;
    _selection.rootPage.numberOfPages = _selTopData.count;
    [_selection.rootPage addTarget:self action:@selector(pageAction:) forControlEvents:UIControlEventValueChanged];
}

#pragma mark -
#pragma mark 创建rootCollectionView
- (void)createRootCollectionView
{
    self.selection = [[Selection alloc]initWithFrame:CGRectMake(0, 0, MAIN_SCREEN_WIDTH, MAIN_SCREEN_HEIGHT)];
    
    self.selection.rootCollectionView.delegate = self;
    self.selection.rootCollectionView.dataSource = self;
    
    
    [_selection.rootCollectionView registerClass:[ProductCollectionViewCell class] forCellWithReuseIdentifier:@"rootCell"];
    
    [self.view addSubview:self.selection];
}

#pragma mark - 设置top滚动视图自动滚动
- (void)AutoScroll
{
    [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(NSTimerActiona) userInfo:nil repeats:YES];
}
#pragma mark - NStimer的响应方法
- (void)NSTimerActiona
{
    [UIView animateWithDuration:0.5 animations:^{
        _pageNum = _selection.rootPage.currentPage;
        _pageNum++;
        _pageNum = _pageNum > (_selTopData.count - 1) ? 0 :_pageNum;
        _selection.rootPage.currentPage = _pageNum;
        [self pageAction:nil];
    }];
}

#pragma mark -
#pragma mark CollectionView必须实现的方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (_selData.count == 0) {
        return 10;
    }
    return _selData.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ProductCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"rootCell" forIndexPath:indexPath];
    
    //    设置圆框
    cell.layer.cornerRadius = 4;
    cell.layer.masksToBounds = YES;
    
    if (_selData.count != 0) {
        cell.proInfo.text = [_selData[indexPath.row] selInfo];
        cell.proInfo.textAlignment = YES;
        
        cell.collectButton.tag = indexPath.row + 1000;
        
        NSURL * imageUrl = [NSURL URLWithString:[_selData[indexPath.row]selImageUrl]];
        [cell.proImage sd_setImageWithURL:imageUrl placeholderImage:[UIImage imageNamed:@"placehold.png"]];
        //    图片自适应
        cell.proImage.contentMode = UIViewContentModeScaleAspectFill;
        cell.collectButton.collectNum.text = [_selData[indexPath.row] selCollectNum];
        
    }
    /**
     *  插入一个“精品”页收藏按钮的响应方法
     *
     *  @param collectButtonAction: 点击之后可以通过coredata收藏到本地沙盒
     *
     */
    //    添加cell上的收藏按钮的响应方法
    [cell.collectButton addTarget:self action:@selector(collectButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    return cell;
}
#pragma mark -
#pragma mark - collectButton的响应事件
- (void)collectButtonAction:(UIButton *)sender
{
    // 判断数组是否获取成功
    if (_selData.count == 0) {
        UIAlertView *netError = [[UIAlertView alloc]initWithTitle:@"网络连接" message:@"网络异常，请重试..." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [netError show];
        return;
    }
//    通过butotn的tag值 获取到数组中所需要的数据
    UIButton *selectButton = sender;
    SelectModel *selectModel = _selData[selectButton.tag -1000];
    
//    获取coredata中所有数据
    [self selectDataFromCoredata];
    
    for (Collect *coll in _DBData) {
        if ([coll.info isEqualToString:selectModel.selInfo]) {
            //            当收藏失败的时候  弹出提示框
            self.CollFailAlert = [[UIAlertView alloc]initWithTitle:@"" message:@"已取消收藏该礼物！" delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
            [_CollFailAlert show];
            //            提示框1秒后自动消失
            [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:NO];
            
            //            发现与数据库中的数据相同
            NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Collect"];
            //            查出该数据
            request.predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"info = '%@'", selectModel.selInfo]];
            //            将该数据保存到临时数组中
            NSArray *temp = [self.managedObjectContex executeFetchRequest:request error:nil];
            //            定义一个新的Collect类型的对象  用来保存查到的数据
            Collect *tempColl = temp[0];
            //            从数据库中删除该元素
            if (tempColl != nil) {
                [self.managedObjectContex deleteObject:tempColl];
                [self.managedObjectContex save:nil];
            }
            return;
        }
    }
//    添加到数据库
    NSEntityDescription *collEntity = [NSEntityDescription entityForName:@"Collect" inManagedObjectContext:self.managedObjectContex];
//    创建Collect 对象
    Collect *coll = [[Collect alloc]initWithEntity:collEntity insertIntoManagedObjectContext:self.managedObjectContex];
//    对Collect对象赋值
    coll.info = selectModel.selInfo;
    coll.image = selectModel.selImageUrl;
    coll.url = selectModel.subUrl;
    
//    保存到数据库
    [self.managedObjectContex save:nil];
    
//    显示“收藏成功”
    self.CollAlert = [[UIAlertView alloc]initWithTitle:@"" message:@"收藏成功!" delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
    [_CollAlert show];
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:NO];
    
}
#pragma mark - 一秒之后 “收藏成功”消失
- (void)timerAction
{
    [_CollFailAlert dismissWithClickedButtonIndex:0 animated:YES];
    [_CollAlert dismissWithClickedButtonIndex:0 animated:YES];
}

#pragma mark - 获取数据库中的持久化数据
- (void)selectDataFromCoredata
{
//    获取coredata中所有的数据
    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Collect"];
    self.DBData = [self.managedObjectContex executeFetchRequest:request error:nil];
    
}

#pragma mark -
#pragma mark 点击item的响应事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    ProDetailViewController *proVC = [[ProDetailViewController alloc]init];
    if (_selData.count != 0) {
        proVC.proDetailUrl = [_selData[indexPath.row] subUrl];
        proVC.proDetailInfo = [_selData[indexPath.row] selInfo];
        proVC.proDetailImage = [_selData[indexPath.row] selImageUrl];
    }    
    [self.navigationController pushViewController:proVC animated:YES];
    
}

#pragma mark -
#pragma mark 定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(ROOT_SEL_SCROLL_HEIGHT + 25, 0, 10, 0);
}

#pragma mark - ScrollView的delegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    self.selection.rootPage.currentPage = _selection.rootScrollView.contentOffset.x / MAIN_SCREEN_WIDTH;
}

#pragma mark - page的响应方法
- (void)pageAction:(id)sender
{
    [UIView animateWithDuration:0.5 animations:^{
        _selection.rootScrollView.contentOffset = CGPointMake(_selection.rootPage.currentPage * MAIN_SCREEN_WIDTH, 0);
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
